package org.iabako.server.servlet;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.poi.util.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by jose on 17/02/15.
 */
public class ImportDataServlet extends HttpServlet {

    static Logger log = Logger.getLogger(ImportDataServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();
        //File size max = 1MB
        upload.setFileSizeMax(1024 * 1024);

        try {
            FileItemIterator iterator = upload.getItemIterator(req);

            String fileName = null;

            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();

                if (item.isFormField() && "importfilename_".equals(item.getFieldName())) {
                    InputStream input = item.openStream();
                    fileName = new String(IOUtils.toByteArray(input));

                } else if (fileName != null) {
                    InputStream input = item.openStream();
                    if (input.available() == 0) {
                        return;
                    }

                    File tmpFile;
                    try {
                        tmpFile = File.createTempFile(fileName, ".xlsx");
                        FileOutputStream out = new FileOutputStream(tmpFile);
                        IOUtils.copy(input, out);
                        out.close();
                        input.close();

                        req.getSession().setAttribute(fileName, tmpFile);

                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                        throw new RuntimeException(e);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
